package org.example.ballgamedemo;

import javafx.beans.property.SimpleStringProperty;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.scene.Scene;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.stage.Stage;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;

import static org.example.ballgamedemo.BouncingBallApp.PREFIX;
import static org.example.ballgamedemo.BouncingBallApp.RECORD_PATH;

public class RankingView extends Stage {
    private TableView<String[]> table = new TableView<>();

    public RankingView() {
        TableColumn<String[], String> nameCol = new TableColumn<>("玩家");
        TableColumn<String[], String> scoreCol = new TableColumn<>("得分");

        nameCol.setCellValueFactory(data -> new SimpleStringProperty(data.getValue()[0]));
        scoreCol.setCellValueFactory(data -> new SimpleStringProperty(data.getValue()[1]));

        table.getColumns().addAll(nameCol, scoreCol);
        table.setItems(loadRecords());
        table.setColumnResizePolicy(TableView.CONSTRAINED_RESIZE_POLICY);

        this.setScene(new Scene(table, 300, 200));
        this.setTitle("排行榜");
    }

    private ObservableList<String[]> loadRecords() {
        ObservableList<String[]> list = FXCollections.observableArrayList();
        try {
            List<String> records = Files.readAllLines(Paths.get(PREFIX + RECORD_PATH));
            records.forEach(line -> {
                String[] parts = line.split(" ");
                if (parts.length >= 2) {
                    list.add(new String[]{parts[0], parts[1]});
                }
            });
        } catch (IOException e) {
            e.printStackTrace();
        }
        return list;
    }
}
